<?php

namespace App\Listeners;

use App\Events\BlogView;
use App\Models\Post;
use Carbon\Carbon;
use Illuminate\Session\Store;

class BlogViewListener
{
    protected $session;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(Store $session)
    {
        $this->session = $session;
//        $this->session->start();
    }

    /**
     * Handle the event.
     *
     * @param  BlogView  $event
     * @return void
     */
    public function handle(BlogView $event)
    {
        /**
         * @var  $post Post
         */
        $post = $event->post;
        //先进行判断是否已经查看过
        if ($post&&!$this->hasViewedBlog($post)) {
            //保存到数据库
            $post->view_count = (int)$post->view_count + 1;
//            dd($post);
            $post->save();
            //看过之后将保存到 Session
            $this->putViewedBlog($post);
        }
    }

    protected function hasViewedBlog($post)
    {
        return $this->session->has($this->getKey($post));
//        return array_key_exists($post->id, $this->getViewedBlogs());
    }

    protected function getViewedBlog($post)
    {
        return $this->session->get($this->getKey($post), []);
    }

    protected function putViewedBlog($post)
    {
        $this->session->put($this->getKey($post), Carbon::now());
    }

    /**
     * @param $post
     * @return string
     */
    protected function getKey($post)
    {
        return 'viewed_blog.' . $post->id;
    }
}
